package com.zhihuishu.micro.course.openapi.course.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import com.zhihuishu.micro.course.constant.CourseTypeEnum;
import com.zhihuishu.micro.course.dto.CourseClipsDto;
import com.zhihuishu.micro.course.dto.CourseDto;
import com.zhihuishu.micro.course.openapi.course.CourseOpenService;
import com.zhihuishu.micro.course.openapi.course.dto.CourseClipsOpenDto;
import com.zhihuishu.micro.course.openapi.course.dto.CourseOpenDto;
import com.zhihuishu.micro.course.openapi.course.dto.MyUniCourseDto;
import com.zhihuishu.micro.course.openapi.course.util.StringUtils;
import com.zhihuishu.micro.course.service.CourseClipsService;
import com.zhihuishu.micro.course.service.CourseService;
import com.zhihuishu.myuni.openapi.common.ICommonRemoteService;
import com.zhihuishu.myuni.openapi.foreignCourse.IForeignCourseRemoteService;
import com.zhihuishu.myuni.openapi.foreignCourse.dto.ShareCourseDto;
import com.zhihuishu.remote.ErrorCode;
import com.zhihuishu.remote.RemoteException;
import com.zhihuishu.remote.RemoteResult;
import com.zhihuishu.toolkit.helper.BeanHelper;

import net.sf.json.JSONObject;


@Service("overSeasCourseOpenService")
public class CourseOpenServiceImpl implements CourseOpenService {

	@Resource
	private CourseService courseService;//课程service层
	@Resource
	private CourseClipsService courseClipsService ;//片花service层
	@Resource
	private ICommonRemoteService iCommonRemoteService;//获取老师认证信息
	@Resource
	private IForeignCourseRemoteService iForeignCourseRemoteService;//创建机构课
	
	/**
	 * 创建一门机构课
	 * 
	 * @param courseName 课程名称
	 * @param schoolId 学校id
	 * @param schoolName 学校名称
	 * @param createUser 用户id（老师id）
	 * 
	 * @return MyUniCourseDto
	 * 
	 * */
	
	//创建一门机构课
	private MyUniCourseDto createMyuniCourse(Long courseId,String courseName, long createUser,Integer type) throws RemoteException{
		
		MyUniCourseDto dto=null;
		//1.查看老师是否有机构
			@SuppressWarnings("rawtypes")
			List list =iCommonRemoteService.listTeacherAuthenticateSchool(createUser);
			String schooIds = null;
			String schooName=null;
			Integer myUniId=null;
			if(list!=null && list.size()>0){
				JSONObject teacher = JSONObject.fromObject(list.get(0));
				schooIds=teacher.getString("schoolId");//学校id
				schooName=teacher.getString("name");//学校名称
				
				//2.创建一门机构课
				if(StringUtils.isNotEmpty(schooIds) && StringUtils.isNotEmpty(schooName)){
					ShareCourseDto shareDto=new ShareCourseDto();
					Assert.notNull(schooIds, "schooId不能为空");
					Integer schooId=Integer.parseInt(schooIds);
					
					shareDto.setOnlineCourseId(courseId.intValue());
					shareDto.setOnlineType(type);//onlineCourse 课程类型
					shareDto.setName(courseName);//课程名称
					shareDto.setTeacherId(new Long(createUser).intValue());//老师id
					shareDto.setSchoolId(schooId);//学校id
					shareDto.setSchoolName(schooName);//学校名称
					shareDto.setUserId(createUser);//课程负责人
					myUniId=iForeignCourseRemoteService.createCourse(shareDto);
					if(myUniId !=null && myUniId >0){
						dto=new MyUniCourseDto(myUniId.longValue(),schooId,schooName,courseName,createUser);
					}
					
				}	
			}
		
		return dto;
	}
	
	@Override
	public RemoteResult<CourseOpenDto> create(String courseName, long createUser) throws RemoteException {
		RemoteResult<CourseOpenDto> remoteResult=new RemoteResult<CourseOpenDto>();
		try {
			Assert.hasLength(courseName, "课程名称不能为空");
			Assert.notNull(createUser, "用户id不能为空");
			
			//创建课程
			CourseDto course = courseService.createOverSeasCourse(courseName,createUser);
			//创建成功
			if(course !=null){
				MyUniCourseDto myUniCourseDto= null;
				if(null != course.getCourseId()){
					//创建机构课
					myUniCourseDto= createMyuniCourse(course.getCourseId(),courseName, createUser,CourseTypeEnum.overSeasCourse.getCode());
				}
				
				Long myUniId=null;
				if(myUniCourseDto !=null && myUniCourseDto.getMyUniId()!=null){
					myUniId=myUniCourseDto.getMyUniId();
				}
				
				//如果老师的机构信息存在，则保存
				if(myUniCourseDto!=null && myUniCourseDto.getSchoolId()!=null && StringUtils.isNotEmpty(myUniCourseDto.getSchoolName())){
					course.setSchoolId(myUniCourseDto.getSchoolId());
					course.setSchoolName(myUniCourseDto.getSchoolName());
					course.setMyuniCourseId(myUniId);
					course.setCourseOpener(2);
				}
				course.setName(courseName);
				course.setCourseMode(1);
				course.setType(CourseTypeEnum.overSeasCourse.getCode());
				course.setTurnType(1);//海外建课默认为校内翻转课程
				courseService.update(course, createUser);
				CourseOpenDto courseOpenDto = BeanHelper.transTo(course,CourseOpenDto.class);
				remoteResult.setResult(courseOpenDto);
				
			}
				
		} catch (Exception e) {
			remoteResult.setSuccess(false);
			throw new RemoteException(e).setMessage("创建课程出错!");
		}
		return remoteResult;
	}
	
	/**
	 * 修改一门机构课 
	 * 
	 * @param courseId 课程id
	 * @param CourseOpenDto 课程对象
	 * 
	 * @return Long
	 */
	
	private Long updateMyuniCourse(CourseOpenDto course)throws RemoteException{	
		CourseDto courseDto=null;
		Long courseId=course.getCourseId();
		
		if(courseId !=null){
			courseDto=courseService.get(courseId);
			
			//如果是机构课，更新机构课信息
			if(courseDto.getMyuniCourseId() !=null && courseDto.getSchoolId() !=null){
				//1.course 获取课程信息的属性值，不为空 添加到myUniCourse对象中
				ShareCourseDto dto=new ShareCourseDto();
				Boolean flag=false;
				
				if(StringUtils.isNotEmpty(course.getName())){//课程名称
					dto.setName(course.getName());
					flag=true;
				}
				if(StringUtils.isNotEmpty(course.getIntroduction())){//课程简介
					dto.setIntroduction(course.getIntroduction());
					flag=true;
				}
				if(StringUtils.isNotEmpty(course.getImg())){//课程封面
					dto.setImg(course.getImg());
					flag=true;
				}
				if(null !=course.getCourseCategory()){//课程类别（1.公共必修课；2.通识必修课；3.专业基础课；4.专业必修课）
					dto.setType(course.getCourseCategory());
					flag=true;
				}
				if(null !=course.getSchoolId()){//学校Id
					dto.setSchoolId(course.getSchoolId());
					flag=true;
				}
//				if(StringUtils.isNotEmpty(course.getSchoolName())){//学校名称
//					dto.setSchoolName(course.getSchoolName());
//					flag=true;
//				}
				if(null !=course.getState()){
					//海外：建课状态（已建课待审核：0，通过审核：1，不通过：2）
					//myuni:'0, 建设中 1, 已发布 2, 申请发布',
					Integer state = course.getState();
					if(state.equals(0)){
						dto.setStatus(2);
					}else{
						dto.setStatus(course.getState());
					}
					flag=true;
				}
				if(null !=course.getMeetCoursePeriod()){//见面课学时
					dto.setTeachTime(course.getMeetCoursePeriod());
					flag=true;
				}
				if(null !=course.getOnlineCoursePeriod()){
					dto.setPracticeTime(course.getOnlineCoursePeriod());//在线学时
					flag=true;
				}
				if(null !=course.getCredit()){//学分
					dto.setCredit(course.getCredit());
					flag=true;
				}
//				if(null !=course.getPeriod()){//总学时
//					dto.setAllTime(course.getPeriod());
//					flag=true;
//				}
				
				//2.如果机myUniCourse对象不为空，更新机构课。
				if(flag){
					//dto.setOnlineCourseId(course.getCourseId().intValue());//课程id (很多数据根据onlineCourseId去查的，更新的时候给他)
					dto.setCourseId(courseDto.getMyuniCourseId().intValue());
					Integer id=iForeignCourseRemoteService.updateCourse(dto);
					if(id >=0){
						return 1L;
					}
				}
				
			}
		}
		
		return null;
	}
	
	@Override
	public RemoteResult<Void> update(CourseOpenDto course, long updateUser) throws RemoteException {
		RemoteResult<Void> result = new RemoteResult<Void>() ;
		// 参数检查
		if(course == null || course.getCourseId() == null) {
			result.setSuccess(false);
			result.setErrorCode(ErrorCode.ARGUMENTS_ILLEGALITY);
			return result ;
		}
		try {
			// 执行本地更新接口
			CourseDto dto = BeanHelper.transTo(course, CourseDto.class) ;
			dto.setType(CourseTypeEnum.overSeasCourse.getCode());
			courseService.update(dto, updateUser);
			
			courseService.touchCourse(course.getCourseId());
			
			//更新myUni课程信息
			updateMyuniCourse(course);
			
		} catch (Exception e) {
			result.setSuccess(false);
			throw new RemoteException(e).setMessage("更新课程执行出错!") ;
		}
		
		return result ;
	}
	
	
	@Override
	public RemoteResult<List<CourseOpenDto>> userCourseList(long userId) throws RemoteException {
		RemoteResult<List<CourseOpenDto>> result=new RemoteResult<List<CourseOpenDto>>();
		try {
			List<CourseDto> courseList = courseService.userCourseList(userId, CourseTypeEnum.overSeasCourse.getCode());
			List<CourseOpenDto> courseOpenList =  new ArrayList<CourseOpenDto>();
			if (!CollectionUtils.isEmpty(courseList)){
				for(CourseDto course : courseList){
					CourseOpenDto courseOpenDto = BeanHelper.transTo(course,CourseOpenDto.class);
					courseOpenList.add(courseOpenDto);
				}
			}
			result.setResult(courseOpenList);
		} catch (Exception e) {
			result.setSuccess(false);
			throw new RemoteException(e).setMessage("查询用户的课程列表出错!") ;
		}
		return result;
	}

    
	@Override
	public RemoteResult<Void> remove(long courseId, long deleteUser) {
		RemoteResult<Void> result=new RemoteResult<Void>();
		try {
			CourseDto courseDto = courseService.get(courseId);
			Assert.notNull(courseId, "课程id不能为空");
			Assert.notNull(deleteUser, "用户id不能为空");
			courseService.remove(courseId, deleteUser);//删除
			//当myuni侧存在数据时，删除myuni数据
			if(null != courseDto && null != courseDto.getMyuniCourseId()){
				iForeignCourseRemoteService.deleteForeignCourse(courseDto.getMyuniCourseId().intValue(),new Long(deleteUser).intValue());
			}
		} catch (Exception e) {
			result.setSuccess(false);
		}
		return null;
	}


	@Override
	public RemoteResult<CourseOpenDto> queryCourseInfo(long courseId) throws RemoteException {
		RemoteResult<CourseOpenDto> remoteResult = new RemoteResult<CourseOpenDto>();
		try{
			CourseDto dto = courseService.get(courseId);
			CourseOpenDto cod = BeanHelper.transTo(dto, CourseOpenDto.class);
			remoteResult.setResult(cod);
		}catch(Exception e){
			remoteResult.setSuccess(false);
			throw new RemoteException(e).setMessage("查询课程信息出错!") ;
		}
		return remoteResult;
	}


	@Override
	public RemoteResult<CourseClipsOpenDto> queryCourseClips(long clipsId) throws RemoteException {
		RemoteResult<CourseClipsOpenDto> result = new RemoteResult<CourseClipsOpenDto>() ;
		try {
			CourseClipsDto clips = courseClipsService.get(clipsId) ;
			result.setResult(BeanHelper.transTo(clips, CourseClipsOpenDto.class)) ;
		} catch (Exception e) {
			throw new RemoteException(e).setMessage("查询课程片花出错!") ;
		}
		
		return result ;
	}


	@Override
	public RemoteResult<Void> updateCourseClips(CourseClipsOpenDto clips) throws RemoteException {
		RemoteResult<Void> result = new RemoteResult<Void>() ;
		// 参数检查
		if(clips == null || clips.getClipsId() == null) {
			result.setSuccess(false);
			result.setErrorCode(ErrorCode.ARGUMENTS_ILLEGALITY);
			return result ;
		}
		try {
			courseClipsService.update(BeanHelper.transTo(clips, CourseClipsDto.class) ,-9L);
		} catch (Exception e) {
			throw new RemoteException(e).setMessage("更新课程片花执行出错!") ;
		}
		
		return result ;
	}


	@Override
	public RemoteResult<Long> createCourseClips(long courseId, CourseClipsOpenDto clips) throws RemoteException {
		RemoteResult<Long> result = new RemoteResult<Long>() ;
		// 参数检查
		if(clips == null) {
			result.setSuccess(false);
			result.setErrorCode(ErrorCode.ARGUMENTS_ILLEGALITY);
			return result ;
		}
		try {
			Long clipsId = courseClipsService.save(courseId, BeanHelper.transTo(clips, CourseClipsDto.class) ,-9L);
			result.setResult(clipsId);
		} catch (Exception e) {
			throw new RemoteException(e).setMessage("更新课程片花执行出错!") ;
		}
		
		return result ;
	}


	@Override
	public RemoteResult<List<CourseOpenDto>> overseasCourseList(List<Long> courseIds) throws RemoteException {
		RemoteResult<List<CourseOpenDto>> result = new RemoteResult<List<CourseOpenDto>>() ;
		if(null == courseIds || courseIds.size() == 0){
			result.setSuccess(true);
			result.setResult(null);
			return result ;
		}
		try {
			List<CourseDto> overseasCourseList = courseService.overseasCourseList(courseIds);
			List<CourseOpenDto> courseOpenList =  new ArrayList<CourseOpenDto>();
			if (!CollectionUtils.isEmpty(overseasCourseList)){
				for(CourseDto course : overseasCourseList){
					if(null != course.getType()){
						if(course.getType().equals( CourseTypeEnum.overSeasCourse.getCode())){
							CourseOpenDto courseOpenDto = BeanHelper.transTo(course,CourseOpenDto.class);
							courseOpenList.add(courseOpenDto);
						}
					}
				}
			}
			result.setSuccess(true);
			result.setResult(courseOpenList);
		} catch (Exception e) {
			result.setSuccess(false);
			throw new RemoteException(e).setMessage("查询海外课程出错!");
		}
		return result;
	}

}
